package org.rbac.serv;

import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.rbac.po.PermissionUsers;
import org.rbac.util.SqlCmdUtil;
import org.rbac.vo.User;
import org.rbac.webservice.Auth;
import org.springframework.beans.BeanUtils;

import com.kingschan.encrypt.CommomEncrypt;

public class AuthServices extends CommonServices implements Auth {

	private final static Logger logger = Logger.getLogger(AuthServices.class);

	/**
	 * 功能：登录检测
	 * 作者：cyc ，kingschan
	 * 开发时间：2017年5月16日 modify :20170526
	 * return :msg:success 代表成功
	 */
	@Override
	public String loginCheck(String loginName, String password,Integer system) {
		JSONObject returnObj=null ;
		try {
			returnObj=new JSONObject();
			if ("".equals(loginName.trim()) || null == loginName) {
				returnObj.put("msg", "用户名不能为空");
				return returnObj.toString();

			}
			if ("".equals(password.trim()) || null == password) {
				returnObj.put("msg", "密码不能为空");
				return returnObj.toString();
			}
			// 计算密码MD5码
			password = CommomEncrypt.MD5(password);
			String hql = "SELECT pu FROM PermissionUsers pu WHERE pu.UStatus = 1 AND pu.UAccount = ? AND pu.UPwd = ?";
			PermissionUsers puser = (PermissionUsers) getDao().uniqueQueryByHql(hql, loginName, password);
			if (null == puser) {
				returnObj.put("msg", "用户名或密码不正确");
				return returnObj.toString();
			}
			String sql = new SqlCmdUtil().getSqlCmdById("openapi", "get_user_permission").getSql();
			List<Map<String, Object>> list = (List<Map<String, Object>>) getDao().executeSQLQuery(sql,system,puser.getId());
			User user = new User();
			BeanUtils.copyProperties(puser,user , new String[]{"UPwd"});

			//查出用户所属部门
			 sql = new SqlCmdUtil().getSqlCmdById("openapi", "get_user_department").getSql();
			List<Map<String, Object>> depetments = (List<Map<String, Object>>) getDao().executeSQLQuery(sql,puser.getUGroup());

			returnObj.put("msg", "success");
			returnObj.put("userId",user.getId().toString());
			returnObj.put("username",user.getUAccount());
			returnObj.put("alias", user.getUAlias());
			returnObj.put("res", JSONArray.fromObject(list));//有权限访问的资源
			returnObj.put("depetments",JSONArray.fromObject(depetments));//有权限访问的资源
			return returnObj.toString();
		} catch (Exception e) {
			returnObj.put("flag", "-1");
			returnObj.put("msg", "服务端出错");
			e.printStackTrace();
			logger.error(e.getMessage());
		}

		return returnObj.toString();
	}

	@Override
	public String getSystemUrl(Integer system) {
		String sql= new SqlCmdUtil().getSqlCmdById("openapi", "get_system_url").getSql();;
		//0白名单 1黑名单 2登录可见
		List<Map<String, Object>> list = (List<Map<String, Object>>) getDao().executeSQLQuery(sql,system);
		JSONArray urls= JSONArray.fromObject(list);
		return urls.toString();
	}


}